package com.logic.system.ws;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.SysCache;
import com.logic.common.util.SysUtil;
import com.logic.system.domain.Mail;
import com.logic.system.domain.Task;
import com.logic.system.service.ITaskService;
import com.logic.system.service.impl.MailService;
import com.logic.system.service.mail.AuditorMailSenderInfoBuilder;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * Created by ronnieking on 5/25/15.
 */

@Path("/emails")
@Api(value = "email", description = "Email Rest WebServices", position = 1)
public class EmailRest
{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private MailService mailService;
    
    @Autowired
    private ITaskService taskService;
    
    @Context
    private HttpServletResponse response;
    
    @Autowired
    AuditorMailSenderInfoBuilder auditorMailSenderInfoBuilder;
    
    @POST
    @Path("/common")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Send email", position = 1)
    public Response testSendEmail()
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            Mail mail = new Mail("daniel.xiao@logicsolutions.com.cn", "This is my subject",
                RandomStringUtils.randomAlphabetic(500));
            mailService.saveAndSendLogicMail(mail);
            map.setResult(CommonResult.SUCCESS, "Create success");
        }
        catch (Exception e)
        {
            logger.error("testSendEmail error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        SysUtil.additionalResonseHeader(map, response);
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    @GET
    @Path("/manual_send_email/{taskId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Send email", position = 1)
    public Response manualSendEmail(@PathParam("taskId") Integer taskId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            Task task = (Task)taskService.get(taskId);
            
            auditorMailSenderInfoBuilder.setTask(task);
            
            mailService.saveAndSendLogicMail(auditorMailSenderInfoBuilder.buildMailSenderInfos());
            
            map.setResult(CommonResult.SUCCESS, "Create success");
        }
        catch (Exception e)
        {
            logger.error("manualSendEmail error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        SysUtil.additionalResonseHeader(map, response);
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    @POST
    @Path("/ftl")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Send ftl email", position = 2)
    public Response testSendFtlEmail()
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            Mail mail = new Mail();
            mail.setMailFrom(SysCache.getInstance().getSysConfig("mail_from"));
            mail.setSubject("test ftl email");
            mail.setMailTo("gary.wang@logicsolutions.com.cn");
            Map<String, String> root = new HashMap<String, String>();
            root.put("test", "test");
            String serverRoot = SysCache.getInstance().getSysConfig("server_root") == null ? ""
                : SysCache.getInstance().getSysConfig("server_root");
            root.put("serverRoot", serverRoot);
            String content = mailService.getFtlContent("test.ftl", root);
            mail.setContent(content);
            mailService.saveAndSendMail(mail);
            map.setResult(CommonResult.SUCCESS, "Create success");
        }
        catch (Exception e)
        {
            logger.error("testSendFtlEmail error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        SysUtil.additionalResonseHeader(map, response);
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
}
